using System.Runtime.Serialization;
using System.Text.Json;
using System.Text.Json.Serialization;

[DataContract]
[KnownType(typeof(LoginRequest))]
[JsonConverter(typeof(LoginRequestJsonConverter))]
public abstract class Base
{
}

[DataContract] //ServiceModel它属于对于可选
public class LoginRequest : Base
{
    [DataMember]
    public string Username { get; set; }

    [DataMember]
    public string Password { get; set; }
}

internal sealed class LoginRequestJsonConverter : JsonConverter<Base>
{
    public override Base Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        object result;
        using (var document = JsonDocument.ParseValue(ref reader))
        {
            var t = typeof(LoginRequest);
            var json = document.RootElement.GetRawText();
            result = JsonSerializer.Deserialize(json, t, options)!;
        }

        return (LoginRequest)result;
    }

    public override void Write(Utf8JsonWriter writer, Base value, JsonSerializerOptions options)
    {
        JsonSerializer.Serialize(writer, value, value.GetType());
    }
}